package com.ldc.security.handle;

import com.ldc.common.utils.ResponseUtils;
import com.ldc.model.utils.ResultUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 定义登录失败时的处理逻辑
 *
 * @auther liudc
 * @since 2022/11/6
 */
@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        String errorMsg = exception.getMessage();
        if (exception instanceof UsernameNotFoundException) {
            errorMsg = "找不到该用户～";
        } else if (exception instanceof BadCredentialsException) {
            errorMsg = "密码错误～";
        } else {
            errorMsg = exception.getMessage();
        }
        ResponseUtils.toResult(response, ResultUtils.toLoginFailed(errorMsg));
    }
}
